<template>
  <div v-if="visible">
    <a-spin :spinning="spinning">
      <div class="employee-selector-wrapper2" style="margin-bottom:30px;">
        <div>
          <div class="employee-selector-block">
            <a-input-search placeholder="搜索人员" style="width: 100%" @search="searchPeople" @change="changePeople" />
          </div>

          <div class="tree-item2" style="margin-top:20px;">
            <div>* 选择成员后可查看该客户专员的客户数据</div>
            <!-- <xq-icon type="icon-wancheng2" v-if="isAllSelected" @click="choseAll(treeData)" class="iconStyle"> </xq-icon>
              <img v-else @click="choseAll(treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;margin-left:10px" /> -->
          </div>
          <div class="employee-selector" style="position:relative;">
            <div v-for="(item, index) in treeData" :key="index" class="mg_t10">
              <div class="tree-item" @click="chose(item, treeData)">
                <span>
                  <img src="@/assets/icons/person1.png" style="width:30px;height:30px;margin-right:10px" />
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ item.name }} {{ item.phone }}</span>
                    </template>
                    <span class="rname" style="width: 210px;">
                      {{ item.name }}
                      {{ item.phone }}
                    </span>
                  </a-tooltip>
                </span>

                <xq-icon v-on:click.stop="chose(item, treeData)" type="icon-wancheng2" v-if="item.isSelected" class="iconStyle"> </xq-icon>
                <img v-else v-on:click.stop="chose(item, treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;" />
              </div>
            </div>
          </div>
          <!-- <a-pagination
              v-model="current"
              size="small"
              :page-size-options="pageSizeOptions"
              :total="total"
              show-size-changer
              show-less-items
              :page-size="pageSize"
              @showSizeChange="onShowSizeChange"
              @change="onPageChange"
            >
              <template slot="buildOptionText" slot-scope="props">
                <span>{{ props.value }}条/页</span>
              </template>
            </a-pagination> -->
        </div>
        <div class="verticalBar" />

        <div class="employee-selector-block2">
          <div class="employee-selector-title">已选择的人员 {{ selectedListTemp.length }} 人</div>
          <div class="employee-selector">
            <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
              <div>
                <img src="@/assets/icons/person1.png" style="width:30px;height:30px; margin-right:10px" />
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ item.name }}</span>
                  </template>
                  <span class="rname">{{ item.name }}</span>
                </a-tooltip>
              </div>
              <img @click="deleteItem(item, i)" src="@/assets/icons/删除.png" style="width:20px;height:20px;" />
            </div>
          </div>
        </div>
      </div>
    </a-spin>
    <div class="btnBox">
      <a-button @click="$emit('upDate', 1)" style="margin-right:12px;">
        上一步
      </a-button>
      <a-button type="primary" @click="ok">
        完成
      </a-button>
    </div>
  </div>
</template>

<script>
import { getAllUser, postAddJurisdiction, putUpdateJurisdiction } from "../api";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ""
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    selectedList: {
      type: Array,
      default: () => []
    },
    permissionsJson: {
      type: Object,
      default: () => {}
    },
    jurisdiction: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      signingStatus: null,
      tabsList: ["全部"],
      spinning: false,
      importDataLength: 0,
      mode: "1",
      treeData: [],
      selectedListTemp: [],
      isAllSelected: false,
      selectedKeysBeforeSearch: [],
      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 1000,
      current: 1,
      total: 50
    };
  },
  watch: {
    visible(val) {
      if (val) {
        // setTimeout(() => {
        //   this.selectedListTemp = [];
        // });

        // this.selectedListTemp = this.selectedList;
        this.treeData = [];
        this.current = 1;
        // this.postTypeValue = 3;
        // this.mode = "1";
        // this.importDataLength = this.selectedList.length;
        // this.onPageChange(1);
        this.spinning = false;
        this.getSelectDepTree();
      }
    }
  },
  created() {
    this.treeData = [];
    this.current = 1;
    this.spinning = false;
    this.getSelectDepTree("", "init");
  },
  methods: {
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    // postTypeClick(value) {
    //   this.postTypeValue = value;
    //   this.isAllSelected = false;
    //   this.current = 1;
    //   this.getSelectDepTree();
    // },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }

      setTimeout(function() {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    // onChangeTab(e) {
    //   this.isAllSelected = false;
    //   this.current = 1;
    //   this.mode = e;
    //   if (e === 0) {
    //     this.signingStatus = "2";
    //   } else if (e === 1) {
    //     this.signingStatus = "0";
    //   } else {
    //     this.signingStatus = "1";
    //   }
    //   this.getSelectDepTree();
    // },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function() {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
          this.isAllSelected = false;
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);

          var count = this.treeData.length;
          var allSelect = true;
          for (var i = 0; i < count; i++) {
            if (!this.treeData[i].isSelected) {
              allSelect = false;
              break;
            }
          }
          this.isAllSelected = allSelect;
        }
      }
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    // 获取树
    getSelectDepTree(query, v) {
      // if (query) {
      //   this.current = 1;
      // }
      const params = {
        id: this.permissionsJson.id,
        status: 2
        // pageSize: this.pageSize,
        // pageNo: this.current,
        // "orders[0].property": "gmtCreate",
        // "orders[0].desc": true
      };
      if (query) {
        params["name"] = query;
      }
      this.spinning = true;
      getAllUser(params)
        .then(res => {
          this.spinning = false;
          if (res.data.entities === null) {
            this.$message.success("暂无数据");
            this.treeData = [];
            this.total = 0;
            this.isAllSelected = false;
          } else {
            // res.data.entities.forEach((item, index) => {
            //   item.id = item.empId;
            // });
            this.treeData = this.formatCompanyData(res.data);
            // this.total = res.data.entityCount;
            var count = res.data.length;
            // this.pageSize = res.data.pageSize;
            // this.current = res.data.pageNo;
            var allSelect = true;
            this.spinning = false;
            if (count !== 0) {
              this.selectedListTemp.forEach(e => {
                this.treeData.forEach(m => {
                  if (e.id === m.id) {
                    m.isSelected = true;
                  }
                });
              });
              for (let i = 0; i < count; i++) {
                if (!this.treeData[i].isSelected) {
                  allSelect = false;
                  break;
                }
              }
              if (v === "init") {
                this.treeData.forEach(e => {
                  e.isSelected = e.isSubordinate;
                  if (e.isSelected) {
                    this.selectedListTemp.push(e);
                  }
                });
              }

              this.isAllSelected = allSelect;
            } else {
              this.isAllSelected = false;
            }
          }
        })
        .catch(err => {
          this.spinning = false;
          console.log("error err --> ", err);
        });
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;

        this.selectedListTemp.forEach((item, index) => {
          if (item.id === company[key].id) {
            selected = true;
          }
        });
        var emp = {};
        emp = {
          id: company[key].id || "",
          name: company[key].name || "",
          phone: company[key].phone || "",
          isSubordinate: company[key].isSubordinate || false
        };
        this.selectedListTemp.forEach((item, index) => {
          item.isSelected = true;
        });

        parent.push(emp);
      }
      this.importDataLength = 0; // 清空传入的默认值
      return parent;
    },
    searchPeople(query) {
      this.selectedKeysBeforeSearch = this.selectedListTemp.map(item => item.id);
      this.getSelectDepTree(query);
    },
    changePeople(e) {
      if (e.target.value === "") {
        this.getSelectDepTree();
        this.selectedKeysBeforeSearch = this.selectedListTemp.map(item => item.id);
      }
    },
    deleteItem(item, index) {
      // this.treeData[index].isSelected = false;
      item.isSelected = false;
      this.treeData.forEach((item2, index2) => {
        if (item2.id === item.id) {
          this.treeData[index2].isSelected = false;
        }
      });
      this.treeData = JSON.parse(JSON.stringify(this.treeData));
      this.spinning = true;

      var that = this;
      setTimeout(function() {
        that.$nextTick(() => {
          that.ergodic(item);
        });

        that.spinning = false;
      }, 100);
    },
    async ok() {
      // if (this.selectedListTemp.length === 0) {
      //   this.$message.warning("请选择人员");
      //   return;
      // }
      // if (this.selectedListTemp.length > 1) {
      //   this.$message.warning("只能选择一名成员新增权限");
      //   return;
      // }
      const arr = this.selectedListTemp.map(item => item.id);
      if (this.type === "add") {
        this.onPostAddJurisdiction(arr);
      } else {
        this.onPutUpdateJurisdiction(arr);
      }

      // this.$emit("upDate", 1, arr[0]);
      // this.$emit("change", this.selectedListTemp);
    },
    async onPostAddJurisdiction(arr) {
      try {
        await postAddJurisdiction({
          jurisdiction: this.jurisdiction,
          name: this.permissionsJson.name,
          phone: this.permissionsJson.phone,
          userId: this.permissionsJson.id,
          memberIds: arr
        });
        this.$notification.success({ message: "配置成功" });
        this.$emit("upDate", "success");
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    async onPutUpdateJurisdiction(arr) {
      try {
        await putUpdateJurisdiction({
          jurisdiction: this.jurisdiction,
          name: this.permissionsJson.name,
          phone: this.permissionsJson.phone,
          id: this.permissionsJson.id,
          memberIds: arr
        });
        this.$notification.success({ message: "配置成功" });
        this.$emit("upDate", "success");
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    upDate() {
      this.visibleT = false;
      this.$emit("update:visible", false);
      this.$emit("upDate");
    },
    setCancel() {
      this.$emit("update:visible", false);
    }
  }
};
</script>
<style lang="scss" scoped>
.postTypeL {
  display: flex;

  flex-direction: row;
  align-items: center;
}
.employee-selector {
  height: 350px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.verticalBar {
  width: 1px;
  background: #e8e8e8;
  display: inline-block;
  // margin-top: 40px;
  vertical-align: top;
  margin-right: 24px;
  margin-left: 24px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  // margin-top: 10px;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 304px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 350px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 260px;
      margin-top: 20px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
.iconStyle {
  margin-left: 10px;
  font-size: 18px;
  color: var(--primary);
}
.btnBox {
  width: 100%;
  height: 56px;
  padding: 12px 12px 0 0;
  position: absolute;
  left: 0;
  bottom: 0;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
}
.rname {
  display: inline-block;
  width: 80px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  vertical-align: middle;
}
</style>
